package com.yl.home.ui

import android.util.Log
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.yl.common.base.BaseVMFragment
import com.yl.common.exp.Constants
import com.yl.common.network.BaseResp
import com.yl.common.network.BaseStateObserver
import com.yl.common.util.ToastUtil
import com.yl.home.R
import com.yl.home.adapter.ArticleAdapter
import com.yl.home.adapter.ArticleItemClickListener
import com.yl.home.adapter.BannerAdapter
import com.yl.home.bean.Article
import com.yl.home.bean.Banner
import com.yl.home.databinding.FragmentHomeBinding
import com.yl.home.viewmodel.HomeViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel

class HomeFragment : BaseVMFragment<FragmentHomeBinding>() {

    private val homeViewModel: HomeViewModel by viewModel()

    lateinit var articleAdapter: ArticleAdapter
    lateinit var lm: LinearLayoutManager

    private var list = ArrayList<Article.ArticleDetail>()
    var isLoadMore = false
    var collectPosition: Int = 0

    override fun getLayoutID() = R.layout.fragment_home


    override fun observe() {
        //轮播图
        homeViewModel.bannerList.observe(this, object : BaseStateObserver<List<Banner>>(null) {

            override fun getRespDataSuccess(it: BaseResp<List<Banner>>) {
                if (it.data!!.isEmpty()) {
                    return
                }

                mBind.banner.refreshData(it.data!!)
            }

            override fun getRespDataEnd() {
                resetUI()
            }
        })

        //文章
        homeViewModel.article.observe(this, object : BaseStateObserver<Article>(null) {
            override fun getRespDataSuccess(it: BaseResp<Article>) {
                resetUI()

                currentPage = it.data!!.curPage - 1

                //下拉刷新
                if (currentPage == 0) {
                    list.clear()
                }

                //最后一页
                if (it.data!!.over) {
                    articleAdapter.isLastPage = true
                }

                //list添加数据
                list.addAll(it.data!!.datas)

                //处理数据
                if (currentPage == 0) {
                    articleAdapter.setData(null)
                    articleAdapter.setData(list)
                    lm.scrollToPosition(0)
                } else {
                    articleAdapter.setData(list)
                }

                Log.d(TAG, "observe articleList: " + list.size)
            }


            override fun getRespDataEnd() {
                resetUI()
            }
        })

        //收藏
        homeViewModel.collectData.observe(this, object : BaseStateObserver<String>(null) {
            override fun getRespDataStart() {
                showLoadingDialog()
            }

            override fun getRespDataEnd() {
                dismissLoadingDialog()
            }

            override fun getRespSuccess() {
                dismissLoadingDialog()
                if (list[collectPosition].collect) {
                    ToastUtil.showMsg("取消收藏！")
                    list[collectPosition].collect = false
                } else {
                    ToastUtil.showMsg("收藏成功！")
                    list[collectPosition].collect = true
                }
                articleAdapter.notifyItemChanged(collectPosition)
            }
        })

    }

    private fun resetUI() {
        isLoadMore = false//加载更多完成，重置false
        if (mBind.swipeLayout.isRefreshing) {
            mBind.swipeLayout.isRefreshing = false
        }
    }

    override fun init() {
        initBanner()
        initList()
        getHomeData()

    }

    private fun initBanner() {
        mBind.banner.apply {
            setAdapter(BannerAdapter())
            setLifecycleRegistry(lifecycle)
            setScrollDuration(600)
            setInterval(5000)
            setAutoPlay(true)
        }.create()
    }

    private fun initList() {
        mBind.recyclerView.setHasFixedSize(true)
        lm = LinearLayoutManager(activity)
        mBind.recyclerView.layoutManager = lm
        mBind.recyclerView.itemAnimator = DefaultItemAnimator()

        articleAdapter = ArticleAdapter(object : ArticleItemClickListener {
            override fun onItemClick(position: Int) {
                val data = list[position]
                ARouter.getInstance()
                    .build(Constants.PATH_WEB)
                    .withString(Constants.WEB_LINK, data.link)
                    .withString(Constants.WEB_TITLE, data.title)
                    .navigation()
            }


            override fun onCollectClick(position: Int) {
                collectPosition = position
                if (list[collectPosition].collect) {
                    homeViewModel.unCollect(list[collectPosition].id)
                } else {
                    homeViewModel.collect(list[collectPosition].id)
                }
            }
        })
        mBind.recyclerView.adapter = articleAdapter


        mBind.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE && articleAdapter.itemCount != 0 &&
                    (lm.findLastVisibleItemPosition() + 1) == articleAdapter.itemCount && !isLoadMore && !articleAdapter.isLastPage
                ) {
                    Log.d(TAG, "onScrollStateChanged: last-----")
                    isLoadMore = true
                    homeViewModel.getArticle(currentPage + 1)
                    Log.d(TAG, "onScrollStateChanged: last-----"+currentPage + 1)
                }
            }
        })

        mBind.swipeLayout.setColorSchemeResources(R.color.theme_color)
        mBind.swipeLayout.setOnRefreshListener {
            articleAdapter.isLastPage = false
            getHomeData()
        }
    }

    private fun getHomeData() {
        homeViewModel.getBanner()
        homeViewModel.getArticle(0)
        resetUI()
    }

    fun scrollToTop() {
        mBind.recyclerView.run {
            if (lm.findFirstVisibleItemPosition() > 20) {
                scrollToPosition(0)
            } else {
                smoothScrollToPosition(0)
            }
        }
    }
}